/* eslint-disable no-undef */
(function ($) {
  const _$editModal = $("#modal-edit-relic");
  const _$editForm = _$editModal.find("form");
  // 预览区文件数组
  let fileList = [];
  // 已上传图片url数组
  let imageUrlList = [];
  // 提示框
  const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000
  });
  // 验证规则
  const vailRule = {
    rules: {
      name: {
        required: true,
      },
      years: {
        required: true,
      },
      ynum: {
        required: true,
      },
      material: {
        required: true,
      },
      count: {
        required: true,
      },
      shelves: {
        required: true,
      },
      size: {
        required: true
      },
      donor: {
        required: true
      }
    },
    messages: {
      name: {
        required: "请输入文物名称",
      },
      years: {
        required: "请输入年代",
      },
      ynum: {
        required: "请输入年号",
      },
      material: {
        required: "请输入材质",
      },
      count: {
        required: "请输入数量",
      },
      shelves: {
        required: "请输入货架号",
      },
      size: {
        required: "请输入尺寸"
      },
      donor: {
        required: "请输入捐赠者"
      }
    },
    errorElement: 'span',
    errorPlacement: function (error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function (element) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function (element) {
      $(element).removeClass('is-invalid');
    }
  };

  const editValidate = _$editForm.validate(vailRule);

  // 点击编辑框
  $("#recordedContainer").on("click", ".toggle-edit-modal-btn", function (e) {
    e.preventDefault();
    let targetUrl = $(this).attr("href");
    $.get(targetUrl, function (data) {
      _$editForm.find("input").each(function () {
        let _$name = $(this).attr("name");
        $(this).val(data[_$name]);
      });
      // 显示仓库
      _$editForm.find("#inputEditWarehouse").find(`option[value = '${data["warehouse"]}']`).prop('selected', true);
      // 初始化已上传区文件数组
      imageUrlList = [];
      // 显示已上传文件
      showUploadImage(data["pic"]);
      // 初始化预览区fileList待上传文件数组
      fileList = [];
      // 初始化二维码显示区域
      if (data["qrPic"]) {
        $("#qrImage").find("a").attr("href", data["qrPic"]).find("img").attr("src", data["qrPic"]);
      }

      _$editModal.modal("show");
    });
  });
  // 关闭编辑框
  _$editModal.find(".close").on("click", closeModalTips);
  _$editModal.find(".cancel-button").on("click", closeModalTips);

  function closeModalTips() {
    Swal.fire({
      title: `您还未提交,确定退出吗`,
      text: "请慎重退出",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#dc3545',
      cancelButtonColor: '#3085d6',
      cancelButtonText: '取消',
      confirmButtonText: '退出'
    }).then((result) => {
      if (result.value) {
        _$editModal.modal('hide');
      }
    });
  }


  // 初始化已上传的图片
  function showUploadImage(imgsurl) {
    let uploadedImageArea = $("#uploadedImageArea");
    let imgUploadedComponentHtml = $("#imgUploadedComponent").html();
    imgsurl.forEach(item => {
      uploadedImageArea.append(imgUploadedComponentHtml);
      uploadedImageArea.find(".img-wapper").last().find("a").eq(0).attr("href", item);
      uploadedImageArea.find(".img-wapper").last().find("img").attr("src", item);
    });
    // 添加
    imageUrlList.push(...imgsurl);
  }

  // 图片上传预览Input=file
  $("#inputFile").on("change", function () {
    let _$this = $(this);
    let file = _$this[0].files;
    if (file[0].size > 1024 * 1024 * 8) { //8M
      return alert("上传图片不能超过8M");
    }
    let reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function () {
      // 动态添加预览图片
      let imgComponentHtml = $("#imgComponent").html();
      $("#previewUploadImages .file").before(imgComponentHtml);
      $("#previewUploadImages").find("a").last().attr("href", this.result).find("img").last().attr("src", this.result);
      // 将文件对象push到fileList中
      fileList.push(file[0]);
      //判断fileList长度是否大于9
      flagFileListLength();
    };
  });

  //判断fileList长度是否大于9
  function flagFileListLength() {
    if (fileList.length > 0) {
      $("#uploadBtn").removeClass("upload-btn-disabled");
    } else {
      $("#uploadBtn").addClass("upload-btn-disabled");
    }
    if (fileList.length >= 9) {
      $("#previewUploadImages .file").css("display", "none");
    } else {
      $("#previewUploadImages .file").css("display", "inline-block");
    }
  }

  // 预览区上传图片按钮
  $("#uploadBtn").on("click", function (e) {
    e.preventDefault();
    let targetUrl = $(this).attr("href");
    const formData = new FormData();
    fileList.forEach(item => {
      formData.append("files[]", item);
    });
    $.ajax({
      url: targetUrl,
      type: 'POST',
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      dataType: 'json',
      success: function (res) {
        if (res.code == 2000) {
          // 请求成功清空预览区,并清空fileList
          $("#previewUploadImages .img-wapper").remove();
          // 将上传成功图片url放到已上传去,
          showUploadImage(res.imgUrlList);
          // 更新上传按钮状态
          flagFileListLength();
          // 重置fileList
          fileList = [];
          Toast.fire({
            type: 'success',
            title: '上传成功',
          });
        } else {
          Toast.fire({
            type: 'error',
            title: '上传失败,' + res.msg,
          });
        }
      },
      error: function (res) {
        Toast.fire({
          type: 'error',
          title: '上传失败,请重试',
        });
      }
    });
  });

  // 监听预览区删除图片按钮
  $("#previewUploadImages").on("click", ".del-btn", function (e) {
    let parent = $(this).parent();
    let index = $("#previewUploadImages .img-wapper").index(parent);
    fileList.splice(index, 1);
    flagFileListLength();
    parent.remove();
  });
  // 监听已上传区删除图片按钮
  $("#uploadedImageArea").on("click", ".del-btn", function (e) {
    e.preventDefault();
    let targetImgUrl = $(this).prev().attr("href");
    let targetUrl = $(this).attr("href");
    let parent = $(this).parent();
    let index = $("#uploadedImageArea .img-wapper").index(parent);
    Swal.fire({
      title: `确定删除文物图片吗?`,
      text: "此操作不可逆,请慎重考虑",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#dc3545',
      cancelButtonText: '取消',
      confirmButtonText: '确定!'
    }).then((result) => {
      if (result.value) {
        $.ajax({
          url: targetUrl,
          type: "get",
          data: targetImgUrl,
          dataType: "json",
          success: function (res) {
            if (res.code == 2000) {
              imageUrlList.splice(index, 1);
              parent.remove();
              Toast.fire({
                type: 'success',
                title: "删除成功",
              });
            } else {
              Toast.fire({
                type: 'error',
                title: '删除失败' + res.msg,
              });
            }
          },
          error: function (err) {
            Toast.fire({
              type: 'error',
              title: '删除失败,请重试',
            });
          }
        });
      }
    });


  });

  // 二维码更换按钮
  $("#qrReplaceInputFile").on("change", function () {
    let _$this = $(this);
    let file = _$this[0].files;
    if (file[0].size > 1024 * 1024 * 8) { //8M
      return alert("上传图片不能超过8M");
    }
    let reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function () {
      $("#qrImage").find("a").attr("href", this.result).find("img").attr("src", this.result);
      $("#qrUpLoadBtn").removeClass("upload-btn-disabled");
    };
  });
  // 二维码上传按钮
  $("#qrUpLoadBtn").on("click", function (e) {
    e.preventDefault();
    let targetUrl = $(this).attr("href");
    let fileData = $("#qrReplaceInputFile")[0].files[0];
    const formData = new FormData();
    formData.append("file", fileData);
    $.ajax({
      url: targetUrl,
      type: 'POST',
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      dataType: 'json',
      success: function (res) {
        if (res.code == 2000) {
          _$editForm.find("input[name='qrPic']").val(res.imgUrl);
          Toast.fire({
            type: 'success',
            title: '上传成功',
          });
        } else {
          Toast.fire({
            type: 'error',
            title: '上传失败' + res.msg,
          });
        }
      },
      error: function (res) {
        Toast.fire({
          type: 'error',
          title: '-----上传失败,请重试-----',
        });
      }
    });
  });
  bsCustomFileInput.init();
  // 选择excel文件
  $("#excelInputFile").on("change", function (e) {
    let fileName = e.target.files[0]; //js 获取文件对象
    if (fileName !== undefined) {
      let file_typename = fileName.name.substring(fileName.name.lastIndexOf('.'));
      if (file_typename === '.xlsx' || file_typename === '.xls') {
        $("#uploadExcelBtn").removeClass("upload-btn-disabled");
      } else {
        $("#uploadExcelBtn").addClass("upload-btn-disabled");
        Toast.fire({
          type: 'error',
          title: '请选择正确的文件类型',
        });
      }
    } else {
      $("#uploadExcelBtn").addClass("upload-btn-disabled");
      Toast.fire({
        type: 'error',
        title: '请选择正确的文件',
      });
    }
  });
  // execl上传
  $("#uploadExcelBtn").on("click", function (e) {
    e.preventDefault();
    let targetUrl = $(this).attr("href");
    const file = $("#excelInputFile")[0].files[0];
    let form = new FormData(); // FormData 对象
    form.append("file", file); // 文件对象

    $.ajax({
      url: targetUrl, //url地址
      type: 'POST', //上传方式
      data: form, // 上传formdata封装的数据
      dataType: 'JSON',
      cache: false, // 不缓存
      processData: false, // jQuery不要去处理发送的数据
      contentType: false, // jQuery不要去设置Content-Type请求头
      success: function (res) { //成功回调
        if (res.code == 2000) {
          $("#modal-import-execl .custom-file-label").text("选择文件");
          $(this).addClass("upload-btn-disabled");
          Toast.fire({
            type: 'success',
            title: '上传成功',
          });
        } else {
          Toast.fire({
            type: 'error',
            title: '上传失败' + res.msg,
          });
        }
      },
      error: function (data) { //失败回调
        Toast.fire({
          type: 'error',
          title: '上传失败,请重试',
        });
      }
    });
  });



  // 提交表单
  function submitEdit(e) {
    if (!_$editForm.valid()) {
      _$editForm.find(".is-invalid").eq(0).focus();
      return;
    }
    if (_$editForm.find("input[name='qrPic']").val() == "") {
      alert("请上传二维码图片");
      return;
    }
    // 为imagesUrl赋值
    _$editForm.find("input[name='imagesUrl']").val(imageUrlList.join(","));
    imageUrlList = [];
    _$editForm.submit();
  }

  // 提交编辑验证表单
  _$editModal.find("#editRelicBtn").on("click", function (e) {
    submitEdit();
  });

  // 点击监听编辑模态框显示与隐藏
  _$editModal.on('shown.bs.modal', () => {
    _$editForm.find('input:not([type=hidden]):first').focus();
  }).on('hidden.bs.modal', () => {
    // 重置编辑表单
    _$editForm[0].reset();
    editValidate.resetForm();
    $("#qrUpLoadBtn").addClass("upload-btn-disabled");
    $("#uploadBtn").addClass("upload-btn-disabled");
    $("#previewUploadImages .img-wapper").remove();
    $("#uploadedImageArea .img-wapper").remove();
  });


  // 不允许点击遮罩层关闭
  _$editModal.modal({
    backdrop: 'static',
    keyboard: false,
    show: false
  });



  // 删除文物对话框
  $("#recordedContainer").on('click', '.delete-confirm-btn', function (e) {
    e.preventDefault();
    let name = $(this).parent().prevAll().eq(9).text();
    // 获取a标签的url
    let targetUrl = $(this).attr("href");
    Swal.fire({
      title: `确定删除文物${name}吗?`,
      text: "此操作不可逆,请慎重考虑",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#dc3545',
      cancelButtonText: '取消',
      confirmButtonText: '确定!'
    }).then((result) => {
      if (result.value) {
        $(location).attr('href', targetUrl);
      }
    });
  });

  // 监听lightbox
  $(document).on('click', '[data-toggle="lightbox"]', function (event) {
    event.preventDefault();
    $(this).ekkoLightbox({
      alwaysShowClose: true
    });
  });
  // 反馈
  let resultStatus = getUrlParam("result");
  if (resultStatus == 1) {
    Toast.fire({
      type: 'success',
      title: '-----删除成功-----',
    });
  } else if (resultStatus == 3) {
    Toast.fire({
      type: 'success',
      title: '-----编辑成功-----',
    });
  }

})(jQuery);